import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { EzFormComponent } from '../ez-form';
import { EzFormControlComponent } from '../ez-form-control';
import { EzFormGroupComponent } from '../ez-form-group';
import { EzFormItemComponent } from '../ez-form-item';
import { EzSelect } from './ez-select';
import { EzSelectConfiguration, EzSelectOptions } from './ez-select.configuration';
@Component({
  selector: 'ez-select',
  templateUrl: './ez-select.component.html',
  styleUrls: ['./ez-select.component.less'],
  providers: [{ provide: EzFormControlComponent, useExisting: EzSelectComponent }],
})
export class EzSelectComponent extends EzFormControlComponent<EzSelectConfiguration, any>
  implements EzSelect, OnInit, OnDestroy {
  defaultMaxSelectCount = Infinity;

  loading = false;

  options: EzSelectOptions = [];

  constructor(
    protected ezForm: EzFormComponent,
    protected ezFormGroup: EzFormGroupComponent,
    protected ezFormItem: EzFormItemComponent
  ) {
    super(ezForm, ezFormGroup, ezFormItem);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.setOptions(
      this.ezFormControlConfiguration.options instanceof Function
        ? this.ezFormControlConfiguration.options(this, this.ezFormGroup, this.ezForm)
        : this.ezFormControlConfiguration.options
    );
  }

  ngOnDestroy(): void {
    super.ngOnDestroy();
  }

  checkConfiguration(configuration: EzSelectConfiguration): void {}

  onBlur(event: KeyboardEvent): void {
    if (this.ezFormControlConfiguration.onBlur) {
      this.ezFormControlConfiguration.onBlur(this, this.ezFormGroup, this.ezForm);
    }
  }

  onFocus(event: KeyboardEvent): void {
    if (this.ezFormControlConfiguration.onFocus) {
      this.ezFormControlConfiguration.onFocus(this, this.ezFormGroup, this.ezForm);
    }
  }

  setOptions(options: EzSelectOptions | Observable<EzSelectOptions> = []): void {
    if (options instanceof Observable) {
      this.loading = true;
      options.subscribe(
        ops => {
          this.loading = false;
          this.options = ops;
        },
        e => {
          this.loading = false;
          console.log(e);
        }
      );
    } else {
      this.options = options;
    }
  }
}
